package com.wasu.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.session.Session;
import org.joda.time.LocalDate;

import com.wasu.bean.AdSchedule;
import com.wasu.util.GlobalInfo;
import com.wasu.util.SerializeUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * jedis 操作order
 * 
 * @author zhouyang
 *
 */
public class OrderJedis {
	private static Logger log = Logger.getLogger(OrderJedis.class);

	private static JedisPool pool = null;

	static {
		pool = new JedisPool(new JedisPoolConfig(), GlobalInfo.REDIS_IP,
				GlobalInfo.REDIS_PORT, 600000);
	}

	/**
	 * 订单写入缓存
	 * 
	 * @param key
	 * @param order
	 */
	public static boolean writeValue(String key, String value) {
		boolean flag = false;
		if (!StringUtils.isEmpty(key)) {
			Jedis jedis = pool.getResource();
			try {
				List<String> tmp = getValues(key);
				if (!tmp.contains(value)) {
					jedis.lpush(key, value); // 存储当天的订单
					flag = true;
				} else {
					log.info(key + "query--订单:" + value + " 写入redis失败,编号已存在");
				}
			} finally {
				if (jedis != null) {
					jedis.close();
				}
			}
		}
		return flag;
	}

	/**
	 * 订单数据写入缓存
	 * 
	 * @param key
	 * @param order
	 */
	public static boolean writeOrderData(String key, List<String> data) {
		boolean flag = false;
		if (!StringUtils.isEmpty(key)) {
			Jedis jedis = pool.getResource();
			try {
				jedis.del(key);
				for (String str : data) {
					jedis.lpush(key, str);
				}
				jedis.expire(key, 3600 * 24);
				flag = true;
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (jedis != null) {
					jedis.close();
				}
			}
		}
		return flag;
	}

	/**
	 * 判断key 是否存在
	 * 
	 * @param key
	 * @return
	 */
	public static boolean existsKey(String key) {
		Jedis jedis = pool.getResource();
		return jedis.exists(key);
	}

	/**
	 * 服务器是否同步任务
	 * @param key
	 * @return
	 */
	public static boolean sync(){
		Jedis jedis = pool.getResource();
		
		try {
			String sync= jedis.get("sync");
			if("yes".equalsIgnoreCase(sync)){
				return true;
			}
		}finally {
			if (jedis != null) {
				jedis.close();
			}

		}
		return false;
	}
	/**
	 * 从缓存读取订单数据
	 * 
	 * @param day
	 * @return
	 */
	public static List<String> readOrderData(String key, int from, int to) {
		List<String> orders = new ArrayList<String>();
		Jedis jedis = pool.getResource();
		try {
			return jedis.lrange(key, from, to);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}

		}
		return orders;

	}

	/**
	 * 从缓存读取订单数据
	 * 
	 * @param day
	 * @return
	 */
	public static long getKeyLen(String key) {
		Jedis jedis = pool.getResource();
		try {
			return jedis.llen(key);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}

		}
		return (long) 0;

	}

	/**
	 * 排期写入缓存
	 * 
	 * @param key
	 * @param order
	 */
	public static boolean writeSchedule(String key, AdSchedule schedule) {
		del(key);
		Jedis jedis = pool.getResource();
		try {
			jedis.set((key).getBytes(), SerializeUtil.serialize(schedule));
			return true;
		} catch (Exception e) {
			//new CustomException("redis服务异常,排期" + schedule.getAdcode() + "///"+ schedule.getExposuredate() + "写入redis失败", e);
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}

		}
		return false;
	}

	/**
	 * 删除Key
	 * 
	 * @param key
	 */
	public static void del(String key) {
		Jedis jedis = pool.getResource();
		try {
			if (jedis.exists(key))
				jedis.del(key);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}

		}
	}

	/**
	 * 暂停订单
	 * 
	 * @param day
	 *            key
	 */
	public static boolean stopOrderKey(String day, String key) {
		Jedis jedis = pool.getResource();
		try {
			if (getValues(day).contains(key)) {
				if (GlobalInfo.SUCCESS_FLAG == jedis.lrem(day, 0, key)) {
					return writeValue(day, key + "_stop");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}

		}

		return false;
	}

	/**
	 * 重启订单
	 * 
	 * @param day
	 *            key
	 */
	public static boolean restartOrderKey(String day, String key) {
		Jedis jedis = pool.getResource();
		try {
			if (getValues(day).contains(key + "_stop")) {
				if (GlobalInfo.SUCCESS_FLAG == jedis
						.lrem(day, 0, key + "_stop")) {
					return writeValue(day, key);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}

		}

		return false;
	}

	/**
	 * 重命名键值
	 * 
	 * @param key
	 */
	public static long renameKey(String key) {
		Jedis jedis = pool.getResource();
		long rst = 0;
		try {
			if (jedis.exists(key)) {
				rst = jedis.renamenx(key, key + "_done");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}

		}
		return rst;
	}

	/**
	 * 从缓存读取订单
	 * 
	 * @param key
	 * @return
	 */
	public static List<String> getValues(String key) {
		List<String> orders = new ArrayList<String>();
		Jedis jedis = pool.getResource();
		try {
			List<String> keys = jedis.lrange(key, 0, -1);
			for (String temp : keys) {
				if (temp.indexOf("_") < 0) {
					orders.add(temp);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}

		}
		return orders;

	}
	
	/**
	 * 从缓存读取订单
	 * 
	 * @param key
	 * @return
	 */
	public static String getValue(String key) {
		Jedis jedis = pool.getResource();
		try {
			return jedis.get(key);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}

		}
		return null;

	}

	/**
	 * 从缓存读取订单
	 * 
	 * @param day
	 * @return
	 */
	public static Session getSession(String key) {

		Jedis jedis = pool.getResource();
		try {
			key="shiro_redis_session:"+key;
			byte[] tmp = jedis.get(key.getBytes());
			if (tmp != null && tmp.length > 0) {
				Session session = (Session) SerializeUtil.unserialize(tmp);
				return session;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}

		}
		return null;

	}
	
	/**
	 * 从缓存读取订单
	 * 
	 * @param day
	 * @return
	 */
	public static AdSchedule readSchedules(String key) {

		Jedis jedis = pool.getResource();
		try {
			byte[] tmp = jedis.get(key.getBytes());
			if (tmp != null && tmp.length > 0) {
				AdSchedule schedule = (AdSchedule) SerializeUtil.unserialize(tmp);
				return schedule;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}

		}
		return null;

	}

	public static int delData(String date, String endwith) {
		Jedis jedis = pool.getResource();
		int i = 0;
		try {
			log.info("clear==============="+"*" + date + endwith);
			Set<String> keys = jedis.keys("*" + date + endwith);
			i = keys.size();
			for (String key : keys) {
				del(key);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}
		}
		return i;
	}

	public static List<AdSchedule> queryAdSchedules(String adcode) {
		List<AdSchedule> list = new ArrayList<AdSchedule>();
		Jedis jedis = pool.getResource();
		log.info("connection:" + jedis.isConnected());
		try {
			Set<String> keys = jedis.keys(adcode + "*");
			for (String key : keys) {
				if (StringUtils.substringAfterLast(key, "_").length() > 4) {
					AdSchedule adSchedule = readSchedules(key);
					list.add(adSchedule);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}
		}
		return list;
	}
	
	public static List<AdSchedule> queryRunSchedules() {
		List<AdSchedule> list = new ArrayList<AdSchedule>();
		Jedis jedis = pool.getResource();
		LocalDate date  = new LocalDate();
		log.info("connection:" + jedis.isConnected());
		try {
			Set<String> keys = jedis.keys("*"+date+"_done");
			for (String key : keys) {
					AdSchedule adSchedule = readSchedules(key);
					if(adSchedule!=null){
						jedis.del(key);
						list.add(adSchedule);
					}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}
		}
		return list;
	}
	
	public static List<AdSchedule> querySchedules() {
		List<AdSchedule> list = new ArrayList<AdSchedule>();
		Jedis jedis = pool.getResource();
		LocalDate date  = new LocalDate();
		log.info("connection:" + jedis.isConnected());
		try {
			Set<String> keys = jedis.keys("*"+date);
			for (String key : keys) {
					AdSchedule adSchedule = readSchedules(key);
					if(adSchedule!=null){
						list.add(adSchedule);
					}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}
		}
		return list;
	}

	public static long lremData(String date, String adcode) {
		Jedis jedis = pool.getResource();
		try {
			return jedis.lrem(date, 1L, adcode);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}
		}
		return 0;
	}
	
	public static long adduser(String key, String field,String value) {
		Jedis jedis = pool.getResource();
		try {
			delusers(key, field);
			jedis.hset(key, field, value);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}
		}
		return 0;
	}
	
	public static Set<String> getUsers(String key) {
		Jedis jedis = pool.getResource();
		try {
			return jedis.hkeys(key);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}
		}
		return null;
	}
	
	public static long delusers(String key, String field) {
		Jedis jedis = pool.getResource();
		try {
			jedis.hdel(key, field);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}
		}
		return 0;
	}
	public static String getPassword(String key, String field) {
		Jedis jedis = pool.getResource();
		try {
			return jedis.hget(key, field);
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				jedis.close();
			}
		}
		return "";
	}

	public static void main(String[] args) {
		// lrem 2016-06-08 0 "b1144862|c1774|i7706" 删除list元素
		List<AdSchedule> list = queryAdSchedules("TA201702281426570813");
		System.out.println(list.size());
		// schedule.setHourrate("[00:00:00=0,01:00:00=0,02:00:00=0,03:00:00=0,04:00:00=0,05:00:00=0,06:00:00=0,07:00:00=0,08:00:00=0,09:00:00=0,10:00:00=0,11:00:00=0,12:00:00=1.0,13:00:00=2.0,14:00:00=3.0,15:00:00=3.1,16:00:00=3.2,17:00:00=3.3,18:00:00=11.49,19:00:00=15.02,20:00:00=16.13,21:00:00=12.17,22:00:00=6.97,23:00:00=2.89]");
		// schedule.setStarttime("18:10:00");
		// schedule.setTxtFile("d:/aaa/TA201608091555040019_USERS.txt");
		// schedule.setTxtFile("/root/simulator/sql/TA201608091558370021_USERS.txt");
		// writeSchedule("TA201608091555040019_2016-08-09",schedule);

		// System.out.println(readOrders("2016-08-04").contains("TA201608011220490003"));
		// stopOrderKey("2016-08-04", "TA201608011220490003");
	}
}
